#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
# author: 小菠萝测试笔记
# blog:  https://www.cnblogs.com/poloyy/
# time: 2021/10/23 10:19 上午
# file: testing_utils.py
"""

__all__ = [
    "get_superuser_token_headers",
    "assert_test_success",
    "assert_test_fail",
    "create_test_data",
    "create_test_user",
]

from typing import Any, Callable, Dict

from fastapi.testclient import TestClient
from requests import Response

from app.config.setting import settings
from tests.utils.data_utils import get_users_test_data


def get_superuser_token_headers(client: TestClient) -> Dict[str, str]:
    login_data = {
        "username": "string",
        "password": "string",
    }
    r = client.post(f"{settings.api_v1_sre}/login/access_token", data=login_data)
    tokens = r.json()
    a_token = tokens["access_token"]
    headers = {"Authorization": f"Bearer {a_token}"}
    return headers


def assert_test_success(res: Response, id: int = 0):
    data = res.json()
    assert res.status_code == 200
    assert data["code"] == 200

    if id:
        assert data["id"] == id


def assert_test_fail(res: Response, code: int, detail: str):
    data = res.json()
    assert res.status_code == code
    assert data["detail"] == detail


def create_test_data(
    path: str, func: Callable, client: TestClient, header: Dict[str, str]
) -> Dict[str, Any]:
    data = func()
    res = client.post(f"{settings.api_v1_sre}/{path}/create", json=data, headers=header)
    return {"name": data["name"], "id": res.json()["id"]}


def create_test_user(client: TestClient, header: Dict[str, str]) -> Dict[str, Any]:
    data = get_users_test_data()
    res = client.post(f"{settings.api_v1_sre}/user/create", json=data, headers=header)
    return {
        "username": data["username"],
        "email": data["email"],
        "name": data["name"],
        "id": res.json()["id"],
    }
